package com.im.web.exception;
import com.im.web.response.Result;
import com.im.web.response.ReturnCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class WebExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(WebExceptionHandler.class);
    /**
     * 处理服务器内异常
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public Result<Object> systemExceptionHandler(Exception e) {
        logger.error("处理服务器内异常{}",e.getMessage());
        return Result.fail(ReturnCode.INTERNAL_SERVER_ERROR, e.getMessage());
    }

    /**
     *  处理请求参数格式错误
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<Object> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        ObjectError objectError = e.getBindingResult().getAllErrors().stream().findFirst().get();
        logger.error("处理请求参数格式错误{}",objectError.getDefaultMessage());
        return Result.fail(ReturnCode.BAD_REQUEST, objectError.getDefaultMessage());
    }
}
